package com.woniuxy.school.online.repair.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.stream.Collectors;

/**
 * 地理位置相关工具
 */
public class AMapUtils {
    private static final String KEY = "ca2b186435e126c21cb690b58140e300";
    private static final String API_URL = "https://restapi.amap.com/v3/geocode/regeo";


    private static String sendGetRequest(String url) throws Exception {
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestMethod("GET");
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
            return reader.lines().collect(Collectors.joining());
        }
    }


    /**
     * 通过经纬度获取地理位置
     * @param lng 经度
     * @param lat 纬度
     * @return
     * @throws Exception
     */
    public static String getAddress(double lng, double lat) throws Exception {
        String url = String.format("%s?location=%s,%s&key=%s&radius=1000",
                API_URL, lng, lat, KEY);
        String response = sendGetRequest(url); // 复用前文sendGetRequest方法
        JSONObject result = JSON.parseObject(response);
        if (result.getIntValue("status") == 1) {
            return result.getJSONObject("regeocode")
                    .getString("formatted_address");
        }
        throw new RuntimeException("请求失败：" + result.getString("info"));
    }


    /**
     * 根据地理位置获取经纬度
     * @param address
     * @return
     * @throws Exception
     */
    public static String[] getLngLat(String address) {
        String urlStr = "https://restapi.amap.com/v3/geocode/geo?key=" + KEY + "&address=" + address;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

            try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
    
                // 解析JSON，提取经纬度（示例）
                JSONObject json = JSON.parseObject(response.toString());
                JSONArray geocodes = json.getJSONArray("geocodes");
                if (geocodes.size() > 0) {
                    String location = geocodes.getJSONObject(0).getString("location"); // 格式："经度,纬度"
                    return location.split(",");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null; // 无结果时返回null
    }

    public static void main(String[] args) throws Exception {
        for (String s : getLngLat("大撒大撒大撒大撒的")) {
            System.out.println(s);
        }
    }
}

